package com.serv.config.swagger;

import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import com.serv.model.boot.User;

/**
 * SwaggerConfig
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig implements EnvironmentAware{

    private RelaxedPropertyResolver applicationPR;
    private RelaxedPropertyResolver serverPR;

    public void setEnvironment(Environment env) {
        this.applicationPR = new RelaxedPropertyResolver(env, "spring.application.");
        this.serverPR = new RelaxedPropertyResolver(env, "server.");
    }

    /**
     * 可以定义多个组，比如本类中定义把test和demo区分开了
     * （访问页面就可以看到效果了） 
     *
     */
    //@Bean
    public <T> Docket testApi(Class<T> clazz) {
        return new Docket(DocumentationType.SWAGGER_2)
                 .groupName("test")
                 //.genericModelSubstitutes(clazz)
                 .ignoredParameterTypes(clazz)
                 .useDefaultResponseMessages(false)
                 .forCodeGeneration(true)//false
                 .pathMapping(serverPR.getProperty("context-path"))// base，最终调用接口后会和paths拼接在一起
                 .select()
                 .paths(PathSelectors.any())
                 //.paths(Predicates.or(PathSelectors.regex("/api/.*")))//过滤的接口
                 .apis(RequestHandlerSelectors.basePackage(applicationPR.getProperty("basePackage")))
                 //.apis(RequestHandlerSelectors.basePackage("com.serv"))
                 .build()
                 .apiInfo(apiInfo());
        }

    @Bean
    public Docket testApi() {
        return testApi(User.class);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
        .title("Spring Boot中使用Swagger2构建RESTful APIs")
        .description("更多Spring Boot相关文章请关注：http://blog.didispace.com/")
        .termsOfServiceUrl("http://blog.didispace.com/")
        .contact("someone")
        .version("1.0")
        .build();
    }

}